package com.jp.knowledge.activity;

import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.ProductInterfaceRightMenuAdapter;
import com.jp.knowledge.adapter.ProductUIAdapter;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIMenuModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.CollectionUiModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/5/11.
 */

public class ProductInterfaceActivityold  extends SlidingActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener{


    private static final int GET_RIGHT_MENU_LIST_CODE = 0x01;
    private static final int REFRESH_DATA_LIST_CODE = 0x02;
    private static final int LOAD_MODE_DATA_LSIT_CODE = 0x03;

    @ViewInject(R.id.icon_right)
    private ImageView openRightBtn;
    @ViewInject(R.id.drawerLayout)
    private DrawerLayout drawerLayout;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView refreshContent;
    @ViewInject(R.id.right_menu)
    private LinearLayout rightMenuView;
    @ViewInject(R.id.right_rv)
    private RecyclerView rightMenuRv;

    private List<ProductUIMenuModel> menuModelList;
    private ProductInterfaceRightMenuAdapter rightMenuAdapter;

    private List<ProductUIModel> productUIModelList;
    private ProductUIAdapter productUIAdapter;
    private ArrayList<String> medias;
    private StaggeredGridLayoutManager gridLayoutManager;

    private String rightMenuCachePath;
    private String productInterfaceDataCachePaht;
    private FileCacheManager cacheManager;

    private int action;
    private int page=1;
    @Override
    protected int getResourceId() {
        return R.layout.activity_product_interface;
    }

    @Override
    protected void init() {
        initTitleBar();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshContent.setHasFixedSize(true);
        action = getIntent() .getIntExtra("action",1);
        gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
//        gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE)；
        refreshContent.setLayoutManager(gridLayoutManager);
        refreshContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                gridLayoutManager.invalidateSpanAssignments();
            }
        });
        rightMenuRv.setHasFixedSize(true);
        rightMenuRv.setLayoutManager(new LinearLayoutManager(mContext));
        rightMenuRv.addItemDecoration(new JpDiver(mContext));

        menuModelList = new ArrayList<>();
        rightMenuAdapter = new ProductInterfaceRightMenuAdapter(mContext, menuModelList);
        rightMenuRv.setAdapter(rightMenuAdapter);
        rightMenuAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if(position == rightMenuAdapter.getSelectedPosition())
                    return;
                rightMenuAdapter.setSelectedPosition(position);
                rightMenuAdapter.notifyDataSetChanged();
                drawerLayout.closeDrawer(rightMenuView);
                refreshContent.scrollToPosition(0);
                refreshLayout.autoRefresh();
            }
        });

        medias = new ArrayList<>();
        productUIModelList = new ArrayList<>();
        productUIAdapter = new ProductUIAdapter(mContext, productUIModelList);
        refreshContent.setAdapter(productUIAdapter);
        productUIAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
//                UiImagePreviewActivity.startActivity(mContext, position, medias);

                Intent intent =new Intent(mContext, PhotoActivity.class);
                intent.putExtra("position",position);
                intent.putExtra("imgs",medias);
                startActivity(intent);
            }
        });

        rightMenuCachePath = mContext.getCacheDir() + "/productInterfaceRightMenu.dat";
        productInterfaceDataCachePaht = mContext.getCacheDir() + "/productInterfaceContentData.dat";
        cacheManager = new FileCacheManager();

        readRightMenuData();
        readProductInterfaceData();
    }

    @Override
    protected void onDestroy() {
        List<ProductUIModel> productUIModels = new ArrayList<>();
        if(productUIModelList.size() <= 20){
            productUIModels.addAll(productUIModelList);
        } else{
            for(int  i = 0; i < 20; i++)
                productUIModels.add(productUIModelList.get(i));
        }
        saveCache(productUIModels, productInterfaceDataCachePaht);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(rightMenuView))
            drawerLayout.closeDrawer(rightMenuView);
        else
            super.onBackPressed();
    }

    private void initTitleBar(){
        topName.setText(getIntent().getStringExtra("name"));
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.VISIBLE);
        openRightBtn.setVisibility(View.VISIBLE);
        openRightBtn.setImageResource(R.mipmap.leidacebianlan);
        leftIcon.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
        openRightBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.icon_serach:
                SearchSimpleActivity.gotoSearch(mContext, 15, -1, null, false);
                break;
            case R.id.icon_right:
                drawerLayout.openDrawer(rightMenuView);
                break;
        }
    }

    private void readRightMenuData(){
        Observable.create(new Observable.OnSubscribe<List<ProductUIMenuModel>>() {
            @Override
            public void call(Subscriber<? super List<ProductUIMenuModel>> subscriber) {
                List<ProductUIMenuModel> data = (List<ProductUIMenuModel>) cacheManager.readObject(rightMenuCachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ProductUIMenuModel>>() {
                    @Override
                    public void onCompleted() {
                        getRightMenuData();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<ProductUIMenuModel> data) {
                        if(data != null) {
                            menuModelList = data;
                            rightMenuAdapter.updateAdapter(menuModelList);
                        }
                        onCompleted();
                    }
                });
    }

    private void readProductInterfaceData(){
        Observable.create(new Observable.OnSubscribe<List<ProductUIModel>>() {
            @Override
            public void call(Subscriber<? super List<ProductUIModel>> subscriber) {
                List<ProductUIModel> data = (List<ProductUIModel>) cacheManager.readObject(productInterfaceDataCachePaht);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ProductUIModel>>() {
                    @Override
                    public void onCompleted() {
                        refreshLayout.autoRefresh();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<ProductUIModel> data) {
                        if(data != null) {
                            productUIModelList = data;
                            productUIAdapter.updateAdapter(productUIModelList);
                            medias.clear();
                            for(CollectionUiModel model : productUIModelList){
//                        medias.add(model.getCover()+"?imageView2/1/interlace/1/format/jpg");
                                medias.add(model.getCover()+"?imageMogr2/format/jpg");//标清图片
                            }
                        }
                        onCompleted();
                    }
                });
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    @Override
    public void onRefresh() {
        getProductInterfaceData(REFRESH_DATA_LIST_CODE);
    }

    @Override
    public void onLoadMore() {
        getProductInterfaceData(LOAD_MODE_DATA_LSIT_CODE);
    }

    private void getRightMenuData(){
        JsonObject param = new JsonObject();
        param.addProperty("action",action);
        HttpHelper.getInstance(mContext).catalogTree(param, GET_RIGHT_MENU_LIST_CODE, this);
    }

    private void getProductInterfaceData(int mode){
        ProductUIMenuModel menuModel;
        try {
            menuModel = menuModelList.get(rightMenuAdapter.getSelectedPosition());
        } catch (Exception e){
            menuModel = null;
        }
        JsonObject param = new JsonObject();
        if(mode == REFRESH_DATA_LIST_CODE) {
            page=1;
            param.addProperty("mode", 0);

        } else{
            page++;
            param.addProperty("mode", 1);
//            if(productUIModelList.size() == 0)
//                param.addProperty("time", System.currentTimeMillis());
//            else
//                param.addProperty("time", productUIModelList.get(productUIModelList.size()-1).getCreatetime());
        }
        param.addProperty("page",page);
        if(menuModel != null)
            param.addProperty("tagId", menuModel.getId());

        param.addProperty("action",action);
        HttpHelper.getInstance(mContext).discoverInterfaceList(param, mode, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_DATA_LIST_CODE)
            refreshLayout.refreshComplete();
        else if(requestType == LOAD_MODE_DATA_LSIT_CODE)
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == GET_RIGHT_MENU_LIST_CODE){
            menuModelList = data.getList(ProductUIMenuModel.class);
            if(menuModelList == null)
                menuModelList = new ArrayList<>();
            ProductUIMenuModel model = new ProductUIMenuModel();
            model.setName("全部");
            menuModelList.add(0, model);
            rightMenuAdapter.updateAdapter(menuModelList);
            saveCache(menuModelList, rightMenuCachePath);
        } else if(requestType == REFRESH_DATA_LIST_CODE || requestType == LOAD_MODE_DATA_LSIT_CODE){
            if(requestType == REFRESH_DATA_LIST_CODE)
                productUIModelList.clear();
            List<ProductUIModel> productUIModels = data.getList(ProductUIModel.class);
            if(productUIModels != null && productUIModels.size() > 0)
                productUIModelList.addAll(productUIModels);
            productUIAdapter.updateAdapter(productUIModelList);

            medias.clear();
            for(CollectionUiModel model : productUIModelList){
                medias.add(model.getCover()+"?imageView2/1/interlace/1/format/jpg");
            }
        }
    }
}
